/**
 * 数据请求工具类
 */
import http from '@ohos.net.http';
import { Log } from '../Log';
export class FetchUtil {

  async get<T>(url: string): Promise<T> {
    const response = await this.request(url, http.RequestMethod.GET);
    if (response.code !== 200) {
      throw new Error(response.msg);
    }
    const data: T = await response.result;
    return data;
  }

  private async request(url: string, method: http.RequestMethod, body?: any): Promise<any> {
    return new Promise((res, rej) => {
      let httpRequest = http.createHttp();
      httpRequest.request(url, {
        method: method,
        extraData: body
      }).then((ret) => {
        Log.info(`request result: ${JSON.stringify(ret)}`);
        if (ret.responseCode === http.ResponseCode.OK) {
          Log.info(`api result: ${JSON.stringify(ret.result)}`);
          res(JSON.parse(ret.result as string));
        }
      }).catch((err) => {
        Log.error(`request failed. Cause: ${JSON.stringify(err)}`);
        rej(err);
      })
    })
  }
}